<template>
  <div>
    <!-- 条件查询 -->
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="data.LeaveName" placeholder="姓名" clearable />
      </el-form-item>

      <el-form-item label="开始时间">
        <el-date-picker
          v-model="data.LeaveStartTime"
          type="date"
          placeholder="请选择一个时间"
          clearable
        />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker
          v-model="data.LeaveEndTime"
          type="date"
          placeholder="请选择一个时间"
          clearable
        />
      </el-form-item>
      <el-form-item label="审批状态">
        <el-select
          v-model="data.ApprovalStatus"
          placeholder="请选择状态"
          style="width: 120px"
          clearable
        >
          <el-option label="待审核" :value="1" />
          <el-option label="审核中" :value="2" />
          <el-option label="已审核" :value="3" />
          <el-option label="已拒绝" :value="4" />
          <el-option label="终审通过" :value="5" />
          <el-option label="终审驳回" :value="6" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getTableData()">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 请假列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="leaveName" label="姓名" />
      <el-table-column prop="departmentId" label="部门">
        <template #default="scope">
          <el-tag v-if="scope.row.departmentId == 1">IF信息部</el-tag>
          <el-tag v-if="scope.row.departmentId == 2">人力资源部</el-tag>
          <el-tag v-if="scope.row.departmentId == 3">财务部</el-tag>
          <el-tag v-if="scope.row.departmentId == 4">销售部</el-tag>
          <el-tag v-if="scope.row.departmentId == 5">行政部</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="leaveType" label="请假类别" />
      <el-table-column prop="leaveStartTime" label="请假时间">
        <template v-slot="scope">
          {{ scope.row.leaveStartTime.substring(0, 10) }} -
          {{ scope.row.leaveEndTime.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="leaveHours" label="总工时" />

      <el-table-column prop="leaveReportTime" label="报到时间">
        <template v-slot="scope">
          {{ scope.row.leaveReportTime.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="leaveReason" label="请假事由" />
      <el-table-column prop="leaderName" label="部门领导" />
      <el-table-column prop="approvalStatusName" label="审批状态" />

      <el-table-column prop="createTime" label="创建时间">
        <template v-slot="scope">
          {{ scope.row.createTime.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间">
        <template v-slot="scope">
          {{
            scope.row.updateTime ? scope.row.updateTime.substring(0, 10) : null
          }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200px">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            @click="upd(scope.row)"
            v-show="
              scope.row.approvalStatus == 1 &&
              store.currentUser.userId == scope.row.leaveId
            "
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            @click="del(scope.row.id)"
            v-show="
              scope.row.approvalStatus == 1 &&
              store.currentUser.userId == scope.row.leaveId
            "
            >删除</el-button
          >
          <el-button
            link
            type="warning"
            @click="app(scope.row)"
            v-show="
              store.currentUser.powerId != 0 &&
              scope.row.approvalStatus != 5 &&
              store.currentUser.userId != scope.row.leaveId &&
              scope.row.approvalStatus != 6 &&
              scope.row.approvalStatus != 4
            "
            >审批</el-button
          >
          <el-button
            v-show="
              scope.row.approvalStatusName == '终审驳回' ||
              scope.row.approvalStatusName == '终审通过' ||
              scope.row.approvalStatusName == '已拒绝'
            "
            link
            type="primary"
            size="small"
            @click="app(scope.row)"
            >审批详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <table style="margin: 15px auto">
      <tr>
        <td>
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            :background="true"
            layout="slot, sizes"
            :total="page.totalCount"
            prev-text="上一页"
            next-text="下一页"
          >
            <span class="page-info">
              当前<span>{{ page.PageSize }}</span
              >条 共<span>{{ page.totalCount }}</span
              >条 当前<span>{{ page.PageIndex }}</span
              >/<span>{{ page.pageCount }}</span
              >页
            </span>
          </el-pagination>
        </td>
        <td>
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            :background="true"
            layout="slot, prev, pager, next"
            :total="page.totalCount"
            prev-text="上一页"
            next-text="下一页"
          >
            <button @click="page.PageIndex = 1" :disabled="page.PageIndex == 1">
              首页
            </button>
          </el-pagination>
        </td>
        <td>
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            :background="true"
            layout="slot, jumper"
            :total="page.totalCount"
            prev-text="上一页"
            next-text="下一页"
          >
            <button
              @click="page.PageIndex = page.pageCount"
              :disabled="page.PageIndex == page.pageCount"
            >
              尾页
            </button>
          </el-pagination>
        </td>
      </tr>
    </table>

    <!-- 修改的弹框 -->
    <el-dialog v-model="dialogVisible" title="编辑请假申请" width="500">
      <template #footer>
        <div class="dialog-footer">
          <el-form :model="form" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名">
              <el-input v-model="form.leaveName" disabled />
            </el-form-item>
            <el-form-item label="部门">
              <el-select
                v-model="form.departmentId"
                placeholder="请选择"
                disabled
              >
                <!-- <el-option :label="divName" :value="form.departmentId" /> -->
                <el-option
                  v-for="item in options"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="请假类别">
              <el-radio-group v-model="form.leaveType">
                <el-radio value="事假">事假</el-radio>
                <el-radio value="病假">病假</el-radio>
                <el-radio value="婚假">婚假</el-radio>
                <el-radio value="丧假">丧假</el-radio>
                <el-radio value="产假">产假</el-radio>
                <el-radio value="补休">补休</el-radio>
                <el-radio value="工伤">工伤</el-radio>
                <el-radio value="其他">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="请假时间" required>
              <el-col :span="11" style="margin-bottom: 15px">
                <el-form-item prop="startTime">
                  <el-date-picker
                    v-model="form.leaveStartTime"
                    aria-label="请选择开始时间"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY年MM月DD日 HH时"
                    value-format="YYYY-MM-DDTHH:mm:ss"
                    style="width: 100%"
                    @change="handleStartTimeChange"
                  />
                </el-form-item>
              </el-col>
              <el-col class="text-center" :span="2" style="margin-bottom: 15px">
                <span class="text-gray-500">&emsp;至</span>
              </el-col>
              <el-col :span="11" style="margin-bottom: 15px">
                <el-form-item prop="endTime">
                  <el-date-picker
                    v-model="form.leaveEndTime"
                    aria-label="请选择开始时间"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY年MM月DD日 HH时"
                    value-format="YYYY-MM-DDTHH:mm:ss"
                    style="width: 100%"
                    @change="handleEndTimeChange"
                  />
                </el-form-item>
              </el-col>
              <span>工时（天和小时）&emsp;</span>
              <el-form-item prop="leaveHoursDisplay">
                <el-input v-model="form.leaveHours" disabled />
              </el-form-item>
            </el-form-item>
            <el-form-item label="总工时">
              <el-input v-model="form.leaveHours" style="width: 50px" />
              <span>（小时）</span>
            </el-form-item>
            <el-form-item label="报到时间">
              <el-date-picker
                v-model="form.leaveReportTime"
                aria-label="请选择报到时间"
                type="datetime"
                placeholder="请选择报到时间"
                format="YYYY年MM月DD日 HH时"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="请假事由">
              <el-input
                v-model="form.leaveReason"
                maxlength="140"
                show-word-limit
                type="textarea"
              />
            </el-form-item>
            <el-form-item label="部门领导">
              <el-input v-model="form.leaderName" disabled />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="okok()">更新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </el-dialog>

    <!-- 审批的弹框 -->
    <el-dialog v-model="dialogVisible1" title="审批" width="500">
      <template #footer>
        <div class="dialog-footer">
          <el-form :model="appData" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名">
              <el-input v-model="appData.leaveName" disabled />
            </el-form-item>
            <el-form-item label="部门">
              <el-select
                v-model="appData.departmentId"
                placeholder="请选择"
                disabled
              >
                <!-- <el-option :label="divName" :value="form.departmentId" /> -->
                <el-option
                  v-for="item in options"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="请假类别">
              <el-radio-group v-model="appData.leaveType">
                <el-radio value="事假">事假</el-radio>
                <el-radio value="病假">病假</el-radio>
                <el-radio value="婚假">婚假</el-radio>
                <el-radio value="丧假">丧假</el-radio>
                <el-radio value="产假">产假</el-radio>
                <el-radio value="补休">补休</el-radio>
                <el-radio value="工伤">工伤</el-radio>
                <el-radio value="其他">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="请假时间" required>
              <el-col :span="11" style="margin-bottom: 15px">
                <el-form-item prop="startTime">
                  <el-date-picker
                    v-model="appData.leaveStartTime"
                    aria-label="请选择开始时间"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY年MM月DD日 HH时"
                    value-format="YYYY-MM-DDTHH:mm:ss"
                    style="width: 100%"
                    @change="handleStartTimeChange"
                  />
                </el-form-item>
              </el-col>
              <el-col class="text-center" :span="2" style="margin-bottom: 15px">
                <span class="text-gray-500">&emsp;至</span>
              </el-col>
              <el-col :span="11" style="margin-bottom: 15px">
                <el-form-item prop="endTime">
                  <el-date-picker
                    v-model="appData.leaveEndTime"
                    aria-label="请选择开始时间"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY年MM月DD日 HH时"
                    value-format="YYYY-MM-DDTHH:mm:ss"
                    style="width: 100%"
                    @change="handleEndTimeChange"
                  />
                </el-form-item>
              </el-col>
              <span>工时（天和小时）&emsp;</span>
              <el-form-item prop="leaveHoursDisplay">
                <el-input v-model="appData.leaveHours" disabled />
              </el-form-item>
            </el-form-item>
            <el-form-item label="总工时">
              <el-input v-model="appData.leaveHours" style="width: 50px" />
              <span>（小时）</span>
            </el-form-item>
            <el-form-item label="报到时间">
              <el-date-picker
                v-model="appData.leaveReportTime"
                aria-label="请选择报到时间"
                type="datetime"
                placeholder="请选择报到时间"
                format="YYYY年MM月DD日 HH时"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="请假事由">
              <el-input v-model="appData.leaveReason" type="textarea" />
            </el-form-item>
            <el-form-item label="审核">
              <el-radio-group v-model="appData.appResult">
                <el-radio :value="1">通过</el-radio>
                <el-radio :value="2">不通过</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="驳回原因"
                v-model="appData.reason"
                v-if="appData.appResult == 2"
              />
            </el-form-item>
            <el-table :data="recordData" style="width: 100%">
              <el-table-column prop="operatorName" label="审批人" width="180" />
              <el-table-column
                v-slot="scope"
                prop="appResult"
                label="审批状态"
                width="180"
              >
                {{ scope.row.appResult == 1 ? "通过" : "不通过" }}
              </el-table-column>
              <el-table-column prop="reason" label="拒绝原因" />
            </el-table>
            <el-form-item>
              <el-button type="primary" @click="ppp()" v-show="aaa == false"
                >确定</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
//import axios from 'axios'
import { axios } from "@/axios/axiosHelp";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useCounterStore } from "@/stores/counter";
const store = useCounterStore();
const router = useRouter();

const data = reactive({
  LeaveName: "",
  LeaveStartTime: "",
  LeaveEndTime: "",
  ApprovalStatus: null,
});

const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
  pageCount: 0,
});

const tableData = ref([]);
const getTableData = () => {
  axios
    .get("/ttest/api/User/QueryLeave", {
      params: {
        UserId: store.currentUser.userId,
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
        LeaveName: data.LeaveName,
        LeaveStartTime: data.LeaveStartTime,
        LeaveEndTime: data.LeaveEndTime,
        ApprovalStatus: data.ApprovalStatus,
        DepartmentId: store.currentUser.departmentId,
      },
    })
    .then((res) => {
      tableData.value = res.data.items;
      page.totalCount = res.data.totalCount;
      page.pageCount = res.data.pageCount;
    });
};

//获取时长

const handleStartTimeChange = () => {
  if (form.leaveStartTime && form.leaveHours) {
    const startTime = new Date(form.leaveStartTime);
    const endTime = new Date(
      startTime.getTime() + form.leaveHours * 60 * 60 * 1000
    );
    form.leaveEndTime = endTime.toISOString().slice(0, 16).replace("T", " ");
  }
  calculateLeaveHours();
};

// 处理结束时间改变
const handleEndTimeChange = () => {
  calculateLeaveHours();
};

// 处理请假工时改变
const handleLeaveHoursChange = () => {
  if (form.leaveStartTime && form.leaveHours) {
    const startTime = new Date(form.leaveStartTime);
    const endTime = new Date(
      startTime.getTime() + form.leaveHours * 60 * 60 * 1000
    );
    form.leaveEndTime = endTime.toISOString().slice(0, 16).replace("T", " ");
  }
  calculateLeaveHours();
};

// 处理报到时间改变
const handleReportTimeChange = () => {
  // 可以在这里添加更多报到时间相关的逻辑
};

// 处理报到时间改变
const calculateLeaveHours = () => {
  const startTime = new Date(form.leaveStartTime);
  const endTime = new Date(form.leaveEndTime);

  const startDay = startTime.getDate();
  const sh = startTime.getHours();
  const endDay = endTime.getDate();
  const eh = endTime.getHours();

  const startHour = sh < 9 ? 9 : sh > 18 ? 18 : sh;
  const endHour = eh < 9 ? 9 : eh > 18 ? 18 : eh;

  if (form.leaveHours !== undefined && form.leaveHours !== null) {
    let days = 0;
    let hours = 0;

    // 完整天计算
    if (startDay < endDay) {
      days = endDay - startDay - 1;

      // 开始天计算
      hours = 18 - startHour - (startHour < 13 ? 1 : 0);

      // 结尾天计算
      hours += endHour - 9 - (endHour > 12 ? 1 : 0);

      // 特殊情况：开头结尾都是满的
      hours === 16 ? ((hours = 0), (days += 2)) : 0;

      // 工时满8进一
      hours >= 8 ? ((hours -= 8), (days += 1)) : 0;
    }
    //开头结尾同天计算
    else if (startDay === endDay) {
      hours = endHour - startHour - (endHour >= 13 && startHour <= 12 ? 1 : 0);
    }

    // 格式化显示工时
    form.leaveHoursDisplay = `${days}天${hours}小时`;
    form.leaveHours = 8 * days + hours;
  } else {
    form.leaveHours = 0;
    form.leaveHoursDisplay = "";
  }
};

//删除
const del = (id: any) => {
  ElMessageBox.confirm("确定删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    axios
      .post("/wtest/api/User/DelLeave", {
        params: {
          Id: id,
        },
      })
      .then((res) => {
        if (res.data.data == 1) {
          ElMessage.success(res.data.msg);
          getTableData();
        }
        if (res.data.data == -1) {
          ElMessage.error(res.data.msg);
        }
      });
  });
};

const dialogVisible = ref(false);
//修改
const upd = (leave: any) => {
  dialogVisible.value = true;
  form.id = leave.id;
  form.leaveId = leave.leaveId;
  form.leaveName = leave.leaveName;
  form.departmentId = leave.departmentId;
  form.leaveType = leave.leaveType;
  form.leaveStartTime = leave.leaveStartTime;
  form.leaveEndTime = leave.leaveEndTime;
  form.leaveHours = leave.leaveHours;
  form.leaveReportTime = leave.leaveReportTime;
  form.leaveReason = leave.leaveReason;
  form.leaderName = leave.leaderName;
  form.approvalStatus = leave.approvalStatus;
  form.approvalStatusName = leave.approvalStatusName;
  form.createUser = leave.createUser;
  form.createTime = leave.createTime;
  form.leaderIds = leave.leaderIds;
};

//修改所需要的参数
const form = reactive({
  id: 0,
  leaveId: store.currentUser.userId,
  leaveName: store.currentUser.name,
  departmentId: store.currentUser.departmentId,
  leaveType: "",
  leaveStartTime: "",
  leaveEndTime: "",
  leaveHours: 0,
  leaveReportTime: "",
  leaveReason: "",
  leaderName: "",
  leaderIds: "",
  createUser: store.currentUser.name,
  createTime: "",
  updateUser: store.currentUser.name,
  approvalStatus: 0,
  approvalStatusName: "",
  leaveHoursDisplay: "",
});

// 定义下拉框选项
const options = ref([
  { id: 1, name: "IF信息部" },
  { id: 2, name: "人力资源部" },
  { id: 3, name: "财务部" },
  { id: 4, name: "销售部" },
  { id: 5, name: "行政部" },
]);

//点击更新
const okok = () => {
  axios.post("/wtest/api/User/UpdateLeave", form).then((res) => {
    if (res.data.data == 1) {
      ElMessage.success(res.data.msg);
      dialogVisible.value = false;
      getTableData();
    }
    if (res.data.data == -1) {
      ElMessage.error(res.data.msg);
    }
  });
};

const dialogVisible1 = ref(false);

//审批需要的参数
const appData = reactive({
  userId: store.currentUser.userId,
  name: store.currentUser.name,
  appResult: null,
  reason: "",
  id: 0,
  leaveId: 0,
  leaveName: "",
  departmentId: 0,
  leaveType: "",
  leaveStartTime: "",
  leaveEndTime: "",
  leaveHours: 0,
  leaveReportTime: "",
  leaveReason: "",
  leaderName: "",
  leaderIds: "",
  approvalStatus: 0,
  approvalStatusName: "",
  createUser: "",
  createTime: "",
  updateUser: store.currentUser.name,
});

//点击审批
const app = (leave: any) => {
  dialogVisible1.value = true;
  (appData.userId = store.currentUser.userId),
    (appData.name = store.currentUser.name),
    (appData.id = leave.id);
  appData.leaveId = leave.leaveId;
  appData.leaveName = leave.leaveName;
  appData.departmentId = leave.departmentId;
  appData.leaveType = leave.leaveType;
  appData.leaveStartTime = leave.leaveStartTime;
  appData.leaveEndTime = leave.leaveEndTime;
  appData.leaveHours = leave.leaveHours;
  appData.leaveReportTime = leave.leaveReportTime;
  appData.leaveReason = leave.leaveReason;
  appData.leaderName = leave.leaderName;

  appData.createUser = leave.createUser;
  appData.createTime = leave.createTime;
  appData.leaderIds = leave.leaderIds;
  getReason();
};

//点击确定
const ppp = () => {
  axios.post("/wtest/api/User/ApprovalLeave", appData).then((res) => {
    if (res.data.data == 1) {
      ElMessage.success(res.data.msg);
      dialogVisible1.value = false;
      getTableData();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//获取原因
const recordData = ref([]);
const aaa: any = ref();
const getReason = () => {
  axios
    .get("/ttest/api/User/QueryReason", {
      params: {
        LeaveId: appData.id,
      },
    })
    .then((res) => {
      recordData.value = res.data.data;
      aaa.value = res.data.data
        .map((x: any) => x.operatorId)
        .includes(store.currentUser.userId);
      console.log(aaa.value);
    });
};

onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.page-info span {
  color: red;
  padding: 2px 5px;
  font-weight: bold;
}
</style>
